<template>
  <bc-container>
    <data-panel ref="dataPanelRef" :columns="columns" :dataSource="tableData" :otherQuery="otherQuery">
      <template #toolbar>
        <el-button type="primary" @click="handleAdd">新增活动</el-button>
      </template>
      <template #action="{ scope }">
        <div class="handle-box">
          <el-button link type="primary" @click="handleEditOrDetail('edit', scope.row)"> 编辑 </el-button>
          <el-button link type="primary" @click="handleDel(scope.row)">删除</el-button>
        </div>
      </template>
    </data-panel>
  </bc-container>
  <bc-modal size="720" type="drawer" :title="formTitle()" v-model="dialogVisible" footer>
    <el-form ref="ruleFormRef" label-position="right" :model="formData" label-width="auto">
      <bc-form ref="bcFormRef" :border="false" :fields="formOptions" :cols="2" :mode="mode" @change="handleChange">
      </bc-form>
      <div class="form-list">
        <bc-form-list
          ref="bcFormListRef"
          :fields="transferOptions"
          :mode="mode"
          @change="handleChangeList"
          keyName="addActivityRewardDTOS"
        />
      </div>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </bc-modal>
</template>

<script setup>
import DataPanel from '@/components/DataPanel.vue'
import BcModal from '@/components/BcModal.vue'
import BcForm from '@/components/bcForm/Index.vue'
import BcFormList from '@/components/bcForm/List.vue'
import { formOptions, columns } from './config'
import { computed, nextTick, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import dayjs from 'dayjs'
const userStore = useUserStore()
const route = useRoute()

/**
 * 列表
 */
const otherQuery = reactive({
  communityId: userStore.communityId,
})
watch(
  () => userStore.communityId,
  () => {
    otherQuery.communityId = userStore.communityId
  }
)
const dataPanelRef = ref()
const tableData = async (params, other) => {
  params = { ...params, ...other }
  const res = await $request.post('/api-parking/parking/activity/queryActivity', { params })
  return {
    rows: (res?.rows || []).map((i) => {
      const imageUrl = i.imageUrl ? [{ url: i.imageUrl }] : null
      const endTime = i.endTime ? dayjs(i.endTime).format('YYYY-MM-DD HH:mm:ss') : null
      return { ...i, imageUrl, endTime }
    }),
    total: res.total ?? 0,
  }
}
const loadData = () => {
  nextTick(() => {
    dataPanelRef.value.load()
  })
}

/**
 * 表单-线索
 */
const transferOptions = computed(() => {
  const communityId = userStore.communityId
  return [
    {
      label: '奖品',
      prop: 'rewardId',
      type: 'select',
      options: async () => {
        try {
          const res = await $request.post('/api-parking/parking/reward/queryReward', {
            params: { communityId, pageSize: 1000, pageNum: 1 },
          })
          return (res?.rows || []).map((item) => ({
            label: item.name,
            value: item.id,
          }))
        } catch (error) {
          return []
        }
      },
    },
    { label: '中奖概率', prop: 'probability' },
    { label: '奖励总数', prop: 'totalAmount' },
    {
      label: '领取频率',
      prop: 'frequency',
      type: 'select',
      options: [
        { label: '每天', value: 'D' },
        { label: '每月', value: 'M' },
        { label: '每年', value: 'Y' },
        { label: '每小时', value: 'H' },
      ],
    },
    { label: '每人限领数量', prop: 'maxPerUser' },
  ]
})
const mode = ref('edit')
const ruleFormRef = ref()
const bcFormRef = ref()
const bcFormListRef = ref()
const dialogVisible = ref(false)
const formData = reactive({})
const formTitle = () => {
  const modeMap = { add: '新增', edit: '编辑' }
  if (mode.value === 'detail') return '活动详情'
  return `${modeMap[mode.value] || ''}活动`
}
const handleChange = (val) => {
  Object.assign(formData, val.value)
}
const handleChangeList = (value) => {
  formData.addActivityRewardDTOS = value
}
const onClose = () => {
  dialogVisible.value = false
}
const onOpen = (val) => {
  dialogVisible.value = true
  Object.keys(formData).forEach((key) => {
    delete formData[key]
  })
  Object.assign(formData, val)
  nextTick(() => {
    bcFormRef.value.set(val)
    bcFormListRef.value.set(val?.addActivityRewardDTOS || [])
    ruleFormRef.value.resetFields()
  })
}
// 新增
const handleAdd = () => {
  mode.value = 'add'
  onOpen({
    communityId: userStore.communityId,
  })
}
// 编辑
const handleEditOrDetail = async (val, scope) => {
  const res = await $request.get('/api-parking/parking/activity/queryActivityById', {
    params: { id: scope.id },
  })
  res['imageUrl'] = res.imageUrl ? [{ url: res.imageUrl }] : null
  res['communityId'] = res?.communityDTOS?.[0]?.id || userStore.communityId
  delete res.communityDTOS
  const info = { ...res, addActivityRewardDTOS: res.activityRewardDTOList || [] }
  mode.value = val
  onOpen(info)
}
// 提交
const handleSubmit = async () => {
  try {
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        const params = { ...formData }
        params['imageUrl'] = params?.imageUrl?.[0].url
        if (!params.communityIds) {
          params.communityIds = [params.communityId]
        }

        await $request.post(
          mode.value === 'add'
            ? '/api-parking/parking/activity/addActivity'
            : '/api-parking/parking/activity/updateActivity',
          { params }
        )
        onClose()
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        // 刷新表单
        loadData()
      }
      return false
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

//  ---- 删除 ----
const handleDel = (info) => {
  const { id } = info
  ElMessageBox.confirm(`是否删除该活动?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 执行删除操作
      await $request.get(`/api-parking/parking/activity/deleteActivity`, {
        params: { id },
      })
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      // 刷新表单
      loadData()
    })
    .catch(() => {
      // 显示取消消息
    })
}
</script>

<style lang="scss" scoped>
.form-list {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background-color: #fff;
  padding: 12px 16px;
  margin-top: 12px;
}
</style>
